﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UltimatePlugin.Settings;
using Zeta;
using Zeta.Common;

namespace UltimatePlugin.Technicals
{
    internal static class Logger
    {
        private static IDictionary<LogCategory, int> _Indentations = new Dictionary<LogCategory, int>();
        private static IDictionary<LogCategory, Stream> _LogFileStreams = new Dictionary<LogCategory, Stream>();
        static Logger()
        {
            foreach (LogCategory category in Enum.GetValues(typeof(LogCategory)))
            {
                _Indentations.Add(category, 0);
            }
        }

        public static void Write(LogSeverity level, LogCategory category, string message, params object[] args)
        {
            if (category == LogCategory.UserInformation)
            {
                Logging.Write(message, args);
            }
            else
            {
                if (!_LogFileStreams.ContainsKey(category))
                {
                    _LogFileStreams.Add(category, File.Open(
                                                    Path.Combine(
                                                        ConfigManager.GetConfig().LogPath, 
                                                        string.Format(
                                                            "{1} - {0} - {2:yymmdd}.txt", 
                                                            category, 
                                                            ZetaDia.Service.CurrentHero.BattleTagName, 
                                                            DateTime.Today)), 
                                                        FileMode.Append,
                                                        FileAccess.Write, 
                                                        FileShare.Read));
                }
                string msgToWrite = string.Format(message, args);
                msgToWrite = string.Format("[{0}] : {2}{1}{3}", level.ToString().Substring(0,1), msgToWrite, " ".PadLeft(_Indentations[category]*4), Environment.NewLine);
                byte[] datas = Encoding.Default.GetBytes(msgToWrite);
                _LogFileStreams[category].Write(datas, 0, datas.Length);
            }
        }

        public static void Write(LogSeverity level, LogCategory category, Exception ex)
        {
            Write(level, category, "{0}", ex.Message);
        }

        internal static void Indent(LogCategory category)
        {
            _Indentations[category]++;
        }

        internal static void Unindent(LogCategory category)
        {
            _Indentations[category]--;
        }
    }
}
